package az.mecid.rssreader.model.dao;

import az.mecid.rssreader.model.entity.FeedEntity;
import az.mecid.rssreader.model.utils.EMF;
import com.google.appengine.api.datastore.Link;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: mega
 * Date: 27.09.2010
 * Time: 1:12:51
 * To change this template use File | Settings | File Templates.
 */
public class FeedDAOImpl implements FeedDAO{
    public FeedEntity save(String url, String title) {
        EntityManager em = EMF.get().createEntityManager();
        Query query = em.createQuery("select e from FeedEntity e where e.url = :url");
        query.setParameter("url", url);
        List<FeedEntity> feeds = query.getResultList();

        FeedEntity feed = null;
        if (feeds.isEmpty()) {
            feed = new FeedEntity(new Link(url), title, System.currentTimeMillis());
            EntityTransaction tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(feed);
                feed = em.merge(feed);
                tx.commit();
            } finally {
                if (tx.isActive())
                    tx.rollback();
            }
        }else{
            feed = feeds.get(0);
        }

        return feed;
    }
}
